/**   
 * @Title: LotteryRecrodTotalAct.java 
 * @Package: com.esun.rabbit2.viewer.mainact.mylotteryact 
 * @Description: (显示竞彩足球购彩记录Activity) 
 * @Author: Billy qigs@500wan.com   
 * @Date: 2011-6-25 下午12:42:48  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.lotteryrecord;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.LotteryRecordInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.LotteryRecordCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: LotteryRecrodTotalAct
 * @Description: (显示竞彩篮球购彩记录)
 * @Author: Billy qigs@500wan.com
 * @Date: 2011-6-25 下午12:42:48
 */
public class LotteryRecordBasketballAct extends Activity implements OnScrollListener, OnRefreshListener, OnItemClickListener {
	private PullToRefreshListView listViewLotteryRecordBasketball; // 全部购彩记录列表
	private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
	private ArrayList<View> itemViewList;
	private LotteryRecordListAdapter adapter;
	private LinearLayout linearFooter; // 列表底部加载布局
	private LinearLayout linearNoMore;
	private LinearLayout linearBottom;
	private ProgressDialog progressDialog;
	public static Handler handlerGetBasketballLotteryRecord;
	private LotteryRecordCommunicater basketballLotteryRecordCommunicater; // 购彩记录接口
	private String serverMessage; // 服务器返回信息
	private int refreshORBottom = 2; // state=1刷新 state=2到底部
	private int pageno = 1;
	private Intent intent;
	private Bundle bundle;
	private LinearLayout linearNoMoreRecord;
	private boolean isShow = true;
	private boolean isRunning;// 是否正在通信
	private boolean isFirstLoad = true; // 是否是第一次加载
	private boolean isNoMoreRecord = true; // 是否还有记录
	private boolean isBottomChanged = false;

	private final int Get_LotteryInfo_SUCCEED = 1001; // 与服务器通信成功、失败
	private final int Get_LotteryInfo_FAIL = 1002;
	private final String LOTID = "47"; // 通信所需参数彩种

	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final int FOOTER_VIEW_TAG3 = 30000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lotteryrecord_basketball_act);

		initUI();
		initHandler();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}

	// 初始化
	public void initUI() {

		isRunning = false;

		progressDialog = ViewerUtil.showProgressDialog(LotteryRecordBasketballAct.this, getResources().getString(R.string.loading_text));
		progressDialog.show();

		listViewLotteryRecordBasketball = (PullToRefreshListView) findViewById(R.id.lotteryrecordbasketballact_listview_lotteryInfoList);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearBottom = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.listview_bottom_view, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);
		linearBottom.setTag(FOOTER_VIEW_TAG3);

		alItem = new ArrayList<Hashtable<String, String>>();
		itemViewList = new ArrayList<View>();
		adapter = new LotteryRecordListAdapter(LotteryRecordBasketballAct.this, alItem, itemViewList, LOTID);
		listViewLotteryRecordBasketball.addFooterView(linearFooter);// 增加底部状态条
		listViewLotteryRecordBasketball.setAdapter(adapter);
		listViewLotteryRecordBasketball.removeFooterView(linearFooter);
		linearNoMoreRecord = (LinearLayout) findViewById(R.id.lotteryrecord_basketballact_linear_noRecord);

		listViewLotteryRecordBasketball.setOnItemClickListener(this);
		listViewLotteryRecordBasketball.setOnRefreshListener(this);
		listViewLotteryRecordBasketball.setOnScrollListener(this);

	}

	// 与服务器通信线程
	public void getDaLeTouLotteryRecordThread() {
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				basketballLotteryRecordCommunicater = new LotteryRecordCommunicater();
				Message msg = new Message();
				try {
					boolean isSucceed = basketballLotteryRecordCommunicater.isGetLotteryRecord(LOTID, String.valueOf(pageno));
					serverMessage = basketballLotteryRecordCommunicater.getServerMsg();
					EDebug.o(this, basketballLotteryRecordCommunicater.getErrorCode());
					if (isSucceed) {
						msg.what = Get_LotteryInfo_SUCCEED;
					} else {
						msg.what = Get_LotteryInfo_FAIL;
					}
					handlerGetBasketballLotteryRecord.sendMessage(msg);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					msg.what = Config.CONNECTION_FAIL;
					handlerGetBasketballLotteryRecord.sendMessage(msg);
				}
			}
		}.start();
	}

	// 消息处理
	public void initHandler() {
		handlerGetBasketballLotteryRecord = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);

				listViewLotteryRecordBasketball.removeFooterView(linearBottom);
				switch (msg.what) {
				case Get_LotteryInfo_SUCCEED:

					pageno++;
					communicateSucceed(basketballLotteryRecordCommunicater.getLotteryRecord());
					itemViewList.clear();
					adapter.notifyDataSetChanged();
					if (basketballLotteryRecordCommunicater.getLotteryRecord().size() < 10) {
						isNoMoreRecord = false;
						listViewLotteryRecordBasketball.addFooterView(linearNoMore);
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Get_LotteryInfo_FAIL:

					// 无更多记录
					if (basketballLotteryRecordCommunicater.getState() == 202) {
						isNoMoreRecord = false;
						if (pageno == 1) {
							// alItem.clear();
							linearNoMoreRecord.setVisibility(View.VISIBLE);
						} else {
							listViewLotteryRecordBasketball.addFooterView(linearNoMore);
						}
					} else {
						// 通讯失败
						if (isShow) {
							//ViewerUtil.showTipDialog(LotteryRecordBasketballAct.this, serverMessage, false);
							Toast.makeText(LotteryRecordBasketballAct.this, serverMessage, 0).show();
						}
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case Config.CONNECTION_FAIL:

					if (isShow) {
						//ViewerUtil.showTipDialog(LotteryRecordBasketballAct.this, Language.STR_CONNECTIONFAIL, false);
						Toast.makeText(LotteryRecordBasketballAct.this, Language.STR_CONNECTIONFAIL, 0).show();
					}
					lengthAutoAdapter();
					endProcess();

					break;

				case com.esun.config.Config.DO_REFRESH:

					if (!isRunning) {
						listViewLotteryRecordBasketball.prepareForRefresh();
						listViewLotteryRecordBasketball.onRefresh();
						progressDialog.show();
					}
					LotteryRecordAgp.isCanClick = true;

					break;

				default:
					break;
				}
			}
		};
	}

	private void endProcess() {
		if (refreshORBottom == 1) {
			listViewLotteryRecordBasketball.onRefreshComplete();
		} else {
			listViewLotteryRecordBasketball.removeFooterView(linearFooter);
		}
		if (progressDialog != null) {
			progressDialog.cancel();
		}
		isRunning = false;
	}

	// 通讯成功处理
	public void communicateSucceed(ArrayList<LotteryRecordInfo> list) {

		ArrayList<Hashtable<String, String>> alItemTemp = new ArrayList<Hashtable<String, String>>();

		for (int i = 0; i < list.size(); i++) {

			// 判断是不是同一天，不是添加title
			if (i == 0) {
				if (alItem.size() > 0) {
					if (!list.get(i).getLotterDate().equals(alItem.get(alItem.size() - 1).get(Key.KEY_ADDDATE))) {
						Hashtable<String, String> mapTitle = new Hashtable<String, String>();

						mapTitle.put(Key.KEY_ISTITLE, "yes");
						mapTitle.put(Key.KEY_ADDDATE, list.get(i).getLotterDate());

						alItemTemp.add(mapTitle);
						groupCount++;
					}
				} else {
					Hashtable<String, String> mapTitle = new Hashtable<String, String>();

					mapTitle.put(Key.KEY_ISTITLE, "yes");
					mapTitle.put(Key.KEY_ADDDATE, list.get(i).getLotterDate());

					alItemTemp.add(mapTitle);
					groupCount++;
				}
			} else {
				if (!list.get(i).getLotterDate().equals(list.get(i - 1).getLotterDate())) {
					Hashtable<String, String> mapTitle = new Hashtable<String, String>();

					mapTitle.put(Key.KEY_ISTITLE, "yes");
					mapTitle.put(Key.KEY_ADDDATE, list.get(i).getLotterDate());

					alItemTemp.add(mapTitle);
					groupCount++;
				}
			}

			Hashtable<String, String> map = new Hashtable<String, String>();
			map.put(Key.KEY_ISTITLE, "no");
			// 显示参数
			map.put(Key.KEY_ADDDATE, list.get(i).getLotterDate());
			map.put(Key.KEY_ADDTIME, list.get(i).getLotterTime());
			map.put(Key.KEY_EXPECT, list.get(i).getExcept());
			map.put(Key.KEY_PAYMONEY, list.get(i).getPayMoney());
			map.put(Key.KEY_PLAYNAME, list.get(i).getPlayName());
			map.put(Key.KEY_GETMONEY, list.get(i).getGetMoney());
			map.put(Key.KEY_STATE, list.get(i).getLotteryState());
			map.put(Key.KEY_ISSUC, list.get(i).getIssuc());
			map.put(Key.KEY_LOTNAME, list.get(i).getLotName());
			// 取详情传递参数
			map.put(Key.KEY_LOTID, list.get(i).getLotID());
			map.put(Key.KEY_UID, list.get(i).getUID());
			map.put(Key.KEY_ID, list.get(i).getID());
			map.put(Key.KEY_PLAYID, list.get(i).getPlayId());

			alItemTemp.add(map);
			childCount++;
		}

		if (refreshORBottom == 1) {
			alItem.clear();
		}
		alItem.addAll(alItemTemp);

	}

	// 到底事件
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
		if ((firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0)) {
			if (isNoMoreRecord) {
				if (isFirstLoad) {
					// listViewLotteryRecordDaLeTou.removeFooterView(linearFooter);
					// listViewLotteryRecordDaLeTou.removeFooterView(linearNoMore);
					// listViewLotteryRecordBasketball.prepareForRefresh();
					// listViewLotteryRecordBasketball.onRefresh();
					isFirstLoad = false;
				} else {
					if (!isRunning && isBottomChanged) {
						isRunning = true;
						isBottomChanged = false;
						listViewLotteryRecordBasketball.addFooterView(linearFooter);
						refreshORBottom = 2;
						getDaLeTouLotteryRecordThread();
					}
				}
			}
		} else {
			isBottomChanged = true;
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	// 判断是否是胆拖，因暂不支持不显示详情
	public boolean isDanTuo(String str) {
		if (str.equals("135") || str.equals("261") || str.equals("264") || str.equals("265")) {
			return true;
		} else if (str.equals("266") || str.equals("267") || str.equals("268") || str.equals("278")) {
			return true;
		} else if (str.equals("279") || str.equals("280")) {
			return true;
		} else {
			return false;
		}
	}

	// 将menu键点击事件返回给父activity处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onTrackballEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		Activity parent = getParent();
		if (parent != null) {
			parent.onTrackballEvent(event);
			return true;
		}
		return false;
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		if (!isRunning) {
			pageno = 1;
			isRunning = true;
			isNoMoreRecord = true;
			refreshORBottom = 1;
			groupCount = 0;
			childCount = 0;
			itemViewList.clear();
			linearNoMoreRecord.setVisibility(View.GONE);
			if (listViewLotteryRecordBasketball.getFooterViewsCount() != 0) {
				listViewLotteryRecordBasketball.removeFooterView(linearNoMore);
			}
			getDaLeTouLotteryRecordThread();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (arg1.getTag() != null
				&& (Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG || Integer.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG2 || Integer
						.parseInt(String.valueOf(arg1.getTag())) == FOOTER_VIEW_TAG3)) {
			return;
		} else {
			if (alItem.get(arg2 - 1).get(Key.KEY_ISTITLE).equals("no")) {
				if (arg2 <= alItem.size()) {
					Hashtable<String, String> strItem = alItem.get(arg2 - 1);
					String tempStrPlayId = strItem.get(Key.KEY_PLAYID);
					if (isDanTuo(tempStrPlayId)) {
						Toast.makeText(LotteryRecordBasketballAct.this, "暂不支持胆拖", Toast.LENGTH_SHORT).show();
					} else {
						intent = new Intent();
						bundle = new Bundle();
						bundle.putString(Key.KEY_LOTID, (String) strItem.get(Key.KEY_LOTID));
						bundle.putString(Key.KEY_ID, (String) strItem.get(Key.KEY_ID));
						bundle.putString(Key.KEY_UID, (String) strItem.get(Key.KEY_UID));
						intent.putExtras(bundle);
						intent.setClass(LotteryRecordBasketballAct.this, LotteryRecordDetailBasketballAct.class);
						startActivity(intent);
					}
				}
			}
		}
	}

	private int groupCount = 0;
	private int childCount = 0;

	private void lengthAutoAdapter() {
		int itemHeight = 30 * groupCount + childCount * (90 + 1);

		// 判断是否需要加入额外item
		if (itemHeight < listViewLotteryRecordBasketball.getHeight()) {
			LinearLayout linearChild = new LinearLayout(this);
			int bheight = 0;
			linearChild.setBackgroundColor(Color.WHITE);
			if (listViewLotteryRecordBasketball.getFooterViewsCount() > 0) {
				bheight = listViewLotteryRecordBasketball.getHeight() - itemHeight - 30;
			} else {
				bheight = listViewLotteryRecordBasketball.getHeight() - itemHeight;
			}
			linearBottom.addView(linearChild);
			for (int i = 0; i < linearBottom.getChildCount(); i++) {
				linearBottom.getChildAt(i).getLayoutParams().height = bheight;
				linearBottom.getChildAt(i).getLayoutParams().width = LayoutParams.FILL_PARENT;
			}
			linearChild.setBackgroundColor(Color.WHITE);
			listViewLotteryRecordBasketball.addFooterView(linearBottom);
		}
	}
}
